package cn.iocoder.yudao.module.member.service.job;

import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.module.infra.api.config.ConfigApi;
import cn.iocoder.yudao.module.member.controller.admin.job.vo.AppJobRespVO;
import cn.iocoder.yudao.module.member.controller.admin.job.vo.JobPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.job.vo.JobSaveReqVO;
import cn.iocoder.yudao.module.member.controller.admin.jobmajor.vo.JobMajorSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.member.dal.dataobject.job.ApiJobDO;
import cn.iocoder.yudao.module.member.dal.dataobject.job.CompanyInfo;
import cn.iocoder.yudao.module.member.dal.dataobject.job.JobApi;
import cn.iocoder.yudao.module.member.dal.dataobject.job.JobDistrict;
import cn.iocoder.yudao.module.member.dal.dataobject.jobintention.JobIntentionDO;
import cn.iocoder.yudao.module.member.dal.dataobject.jobmajor.JobMajorDO;
import cn.iocoder.yudao.module.member.dal.dataobject.major.MajorDO;
import cn.iocoder.yudao.module.member.dal.mysql.company.CompanyMapper;
import cn.iocoder.yudao.module.member.dal.mysql.job.ApiJobMapper;
import cn.iocoder.yudao.module.member.dal.mysql.job.CompanyInfoMapper;
import cn.iocoder.yudao.module.member.dal.mysql.job.JobApiMapper;
import cn.iocoder.yudao.module.member.dal.mysql.job.JobDistrictMapper;
import cn.iocoder.yudao.module.member.dal.mysql.jobintention.JobIntentionMapper;
import cn.iocoder.yudao.module.member.dal.mysql.jobmajor.JobMajorMapper;
import cn.iocoder.yudao.module.member.dal.mysql.major.MajorMapper;
import cn.iocoder.yudao.module.member.service.config.MemberConfigService;
import cn.iocoder.yudao.module.member.service.jobmajor.JobMajorService;
import cn.iocoder.yudao.module.member.service.major.MajorService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.JOB_NOT_EXISTS;

/**
 * 职位 Service 实现类
 *
 * @author Alan
 */
@Service
@Validated
public class ApiJobServiceImpl implements ApiJobService {
    @Resource
    private JobIntentionMapper jobIntentionMapper;
    @Resource
    private ApiJobMapper apiJobMapper;

    @Resource
    private JobMajorService jobMajorService;
    @Resource
    private JobMajorMapper jobMajorMapper;
    @Resource
    private MajorService majorService;

    @Resource
    private MajorMapper majorMapper;
    @Resource
    CompanyMapper companyMapper;
    @Resource
    private ConfigApi configApi;
    @Resource
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private JobApiMapper jobApiMapper;
    @Resource
    private JobDistrictMapper jobDistrictMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncJob() {
        List<JobApi> jobApis = jobApiMapper.selectList();
        List<JobMajorDO> jobMajorDOS =new ArrayList<>();
        for (JobApi api: jobApis) {
            if (StringUtils.isNotBlank(api.getMajorCn())) {
                String[] split = api.getMajorCn().split(",");
                for (String str: split) {
                    List<MajorDO> majorDOS = majorMapper.selectList(new LambdaQueryWrapper<MajorDO>()
                            .eq(MajorDO::getName, str));
                    if (!CollectionUtils.isEmpty(majorDOS)) {
                        JobMajorDO jobMajorDO =new JobMajorDO();
                        jobMajorDO.setJobId(Long.valueOf(api.getJobId()));
                        jobMajorDO.setMajorId(majorDOS.get(0).getId());
                        jobMajorDO.setMajorName(majorDOS.get(0).getName());
                        jobMajorDOS.add(jobMajorDO);
                    }
                }
            }
        }
        jobMajorMapper.insertOrUpdate(jobMajorDOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sync() {
        List<CompanyInfo> companyInfos = companyInfoMapper.selectList();
        List<CompanyDO> companyDOS = new ArrayList<>();
        for (CompanyInfo info:companyInfos) {
            CompanyDO companyDO = new CompanyDO();
            companyDO.setId(Long.valueOf(info.getCompanyId()    ));
            companyDO.setAddress(info.getAreaCn());
            companyDO.setCompanyName(info.getName());
            companyDO.setCompanyNature(info.getNatureCn());
            companyDO.setCompanyProfile("");
            companyDO.setCompanyScale(info.getScaleCn());
            companyDO.setCompanyWelfare("");
            companyDO.setPhone("");
            String[] split = info.getAreaCode().split("-");
            String[] name = info.getAreaCn().split("-");

// 遍历有效的split和name数组长度中的最小值，避免数组越界异常
            int minLength = Math.min(split.length, name.length);

            if (minLength > 2) {
                // 设置城市信息，确保split[2]存在
                companyDO.setCityId(Long.valueOf(split[2]));
                companyDO.setCityName(name[2]);
            }

            if (minLength > 3) {
                // 设置区域信息，确保split[3]存在
                companyDO.setDistrictId(Long.valueOf(split[3]));
                companyDO.setDistrictName(name[3]);
            }

            if (minLength > 1) {
                // 设置省份信息，确保split[1]存在
                companyDO.setProvinceId(Long.valueOf(split[1]));
                companyDO.setProvinceName(name[1]);
            } else {

            }
            companyDO.setContacts("");
            companyDO.setMail("");
            companyDO.setIndustry(info.getIndustryCn());
            companyDO.setSuperEmployer(false);
            companyDO.setLogoUrl(info.getShowLogo());
            companyDOS.add(companyDO);
        }
        companyMapper.insertOrUpdate(companyDOS);
        List<JobApi> jobApis = jobApiMapper.selectList();
        List<JobDistrict> jobDistrict = jobDistrictMapper.selectList();
        List<ApiJobDO> jobDOS = new ArrayList<>();
        for (JobApi api: jobApis) {
            ApiJobDO apiJobDO = new ApiJobDO();
            apiJobDO.setId(Long.valueOf(api.getJobId()));
            apiJobDO.setJobName(api.getJobName());
            apiJobDO.setCompanyId(Long.valueOf(api.getCompanyId()));
            apiJobDO.setClassRequirements(api.getExperienceCn());
            apiJobDO.setMinEducation(api.getEducationCn());
            JobDistrict jobDistrict1 = jobDistrict.stream().filter(v1 -> v1.getJobId().equals(api.getJobId())).findFirst().orElse(null);
            if (Objects.nonNull(jobDistrict1)) {
                if (StringUtils.isNotBlank(jobDistrict1.getProvince())) {
                    apiJobDO.setProvinceId(Long.valueOf(jobDistrict1.getProvince()));
                    Area area = AreaUtils.getArea(Integer.valueOf(jobDistrict1.getProvince()));
                    if (Objects.nonNull(area)) {
                        apiJobDO.setProvinceName(area.getName());
                    }

                }
                if (StringUtils.isNotBlank(jobDistrict1.getCity())) {
                    System.out.println("---------------------------------城市"+jobDistrict1.getCity()+"数据id"+jobDistrict1.getId());
                    apiJobDO.setCityId(Long.valueOf(jobDistrict1.getCity()));
                    Area area = AreaUtils.getArea(Integer.valueOf(jobDistrict1.getCity()));
                    if (Objects.nonNull(area)) {
                        apiJobDO.setCityName(area.getName());
                    }

                }
                if (StringUtils.isNotBlank(jobDistrict1.getDistrict())) {
                    //System.out.println("---------------------------------区县"+jobDistrict1.getDistrict()+"数据id"+jobDistrict1.getId());
                    apiJobDO.setDistrictId(Long.valueOf(jobDistrict1.getDistrict()));
                    Area area = AreaUtils.getArea(Integer.valueOf(jobDistrict1.getDistrict()));
                    if (Objects.nonNull(area)) {
                        apiJobDO.setDistrictName(area.getName());
                    }

                }
                apiJobDO.setAddress(jobDistrict1.getAreaCn());
            }
            apiJobDO.setJobDetail(api.getContents());
            apiJobDO.setIsShelved(true);
            apiJobDO.setShelvedTime(LocalDateTime.now());
            apiJobDO.setIsRecommend(false);
            apiJobDO.setRecommendTime(LocalDateTime.now());
            apiJobDO.setHireBeginTime(api.getStartTime());
            apiJobDO.setHireEndTime(api.getEndTime());
            apiJobDO.setUrl("");
            apiJobDO.setJobType(api.getNatureCn());
            jobDOS.add(apiJobDO);
        }
        apiJobMapper.insertOrUpdate(jobDOS);
    }

    @Override
    public Long createJob(JobSaveReqVO createReqVO) {
        Set<Long> majorId = createReqVO.getMajorId();
        createReqVO.setMajorId(null);
        // 插入
        ApiJobDO job = BeanUtils.toBean(createReqVO, ApiJobDO.class);
        apiJobMapper.insert(job);
        majorId.forEach(v1-> {
            MajorDO major = majorService.getMajor(v1);
            JobMajorSaveReqVO reqVO =new JobMajorSaveReqVO();
            reqVO.setJobId(job.getId());
            reqVO.setMajorId(major.getId());
            reqVO.setMajorName(major.getName());
            jobMajorService.createJobMajor(reqVO);
        });
        // 返回
        return job.getId();
    }

    @Override
    public void updateJob(JobSaveReqVO updateReqVO) {
        Set<Long> majorId = updateReqVO.getMajorId();
        updateReqVO.setMajorId(null);
        // 校验存在
        validateJobExists(updateReqVO.getId());
        // 更新
        ApiJobDO updateObj = BeanUtils.toBean(updateReqVO, ApiJobDO.class);
        apiJobMapper.updateById(updateObj);
        jobMajorService.deleteJobIdMajor(updateReqVO.getId());
        majorId.forEach(v1-> {
            MajorDO major = majorService.getMajor(v1);
            JobMajorSaveReqVO reqVO =new JobMajorSaveReqVO();
            reqVO.setJobId(updateReqVO.getId());
            reqVO.setMajorId(major.getId());
            reqVO.setMajorName(major.getName());
            jobMajorService.createJobMajor(reqVO);
        });
    }

    @Override
    public void deleteJob(Long id) {
        // 校验存在
        validateJobExists(id);
        // 删除
        apiJobMapper.deleteById(id);
        jobMajorService.deleteJobIdMajor(id);
    }

    private void validateJobExists(Long id) {
        if (apiJobMapper.selectById(id) == null) {
            throw exception(JOB_NOT_EXISTS);
        }
    }

    @Override
    public ApiJobDO getJob(Long id) {
        ApiJobDO apiJobDO = apiJobMapper.selectById(id);
        List<JobMajorDO> jobMajorDOS = jobMajorMapper.selectList(new LambdaQueryWrapper<JobMajorDO>()
                .eq(JobMajorDO::getJobId, id));
        if (!CollectionUtils.isEmpty(jobMajorDOS)) {
            String majorNames = jobMajorDOS.stream()
                    .map(JobMajorDO::getMajorName)
                    .collect(Collectors.joining(","));
            apiJobDO.setMajorName(majorNames);
        }
        return apiJobDO;
    }

    @Override
    public ApiJobDO getJobs(Long jobId) {
        ApiJobDO apiJobDO = apiJobMapper.selectById(jobId);
        return apiJobDO;
    }

    @Override
    public PageResult<ApiJobDO> getJobPage(JobPageReqVO pageReqVO) {
        return apiJobMapper.selectPage(pageReqVO);
    }

    @Override
    public Long jobStatistics() {
        Long re = apiJobMapper.selectCount(new LambdaQueryWrapper<ApiJobDO>()
                .eq(ApiJobDO::getIsShelved, true)
        );
        String total = configApi.getConfigValueByKey("当前可报");
        if (StringUtils.isNotBlank(total)) {
            if (Long.valueOf(total) >0 ) {
                re = Long.valueOf(total);
            }
        }
        return re;
    }

    @Override
    public Long jobAddStatistics() {
        // 获取当前时间减去24小时前的时间
        LocalDateTime twentyFourHoursAgo = LocalDateTime.now().minusHours(24);
        Long re = apiJobMapper.selectCount(new LambdaQueryWrapper<ApiJobDO>()
                        .isNotNull(ApiJobDO::getShelvedTime)
                .eq(ApiJobDO::getIsShelved, true)
                .ge(ApiJobDO::getShelvedTime, twentyFourHoursAgo) // shelvedTime >= 24小时前
        );
        String total = configApi.getConfigValueByKey("24h");
        if (StringUtils.isNotBlank(total)) {
            if (Long.valueOf(total) > 0 ) {
                re = Long.valueOf(total);
            }
        }
        return re;
    }

    @Override
    public PageResult<AppJobRespVO> getJobAddList(JobPageReqVO pageReqVO) {
        Page<AppJobRespVO> page = new Page<AppJobRespVO>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        JobIntentionDO jobIntentionDO = jobIntentionMapper.selectOne(new LambdaQueryWrapper<JobIntentionDO>()
                .eq(JobIntentionDO::getUserId, getLoginUserId()).last("limit 1"));
        //按照学历、岗位类型、意向地区
        if (!"3".equals(pageReqVO.getType())) {
            if (Objects.nonNull(jobIntentionDO)) {
                pageReqVO.setJobType(jobIntentionDO.getJobType());
                pageReqVO.setCityName(jobIntentionDO.getCityName());
                pageReqVO.setMinEducation(jobIntentionDO.getEducationalBackground());
                pageReqVO.setCompanyNature(jobIntentionDO.getEnterpriseNature());
                pageReqVO.setMajorName(jobIntentionDO.getMajorName());
            }
        }

        IPage<AppJobRespVO> user = apiJobMapper.getJobAddList(page,pageReqVO);
        return new PageResult<>(user.getRecords(),user.getTotal());
    }

    @Override
    public PageResult<AppJobRespVO> getJobListPage(JobPageReqVO pageReqVO) {
        Page<AppJobRespVO> page = new Page<AppJobRespVO>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        if (StringUtils.isNotBlank(pageReqVO.getCompanyNature())) {
            String[] split = pageReqVO.getCompanyNature().split(",");
            pageReqVO.setCompanyNatures(Arrays.asList(split)); // 多个值
        }
        if (StringUtils.isNotBlank(pageReqVO.getJobType())) {
            String[] split = pageReqVO.getJobType().split(",");
            pageReqVO.setJobTypes(Arrays.asList(split)); // 多个值
            pageReqVO.setJobType("");
        }
        if (StringUtils.isNotBlank(pageReqVO.getMinEducations())) {
            String[] split = pageReqVO.getMinEducations().split(",");
            pageReqVO.setMins(Arrays.asList(split)); // 多个值
        }
        IPage<AppJobRespVO> user = apiJobMapper.getJobListPage(page,pageReqVO);
        return new PageResult<>(user.getRecords(),user.getTotal());
    }

    @Override
    public List<Map> getJobListList(String name) {
        return apiJobMapper.getJobListList(name);
    }
}